#!/bin/bash

# 工程实践平台停止脚本
# 使用方法: ./scripts/stop.sh

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查脚本是否在项目根目录运行
check_project_root() {
    if [[ ! -f "pom.xml" ]] && [[ ! -f "app.jar" ]]; then
        log_error "请在项目根目录运行此脚本"
        exit 1
    fi
}

# 停止主应用
stop_main_app() {
    log_info "停止主应用..."
    
    if [[ -f "app.pid" ]]; then
        local PID=$(cat app.pid)
        if kill -0 $PID 2>/dev/null; then
            log_info "停止应用进程 (PID: $PID)..."
            
            # 尝试优雅停止
            kill $PID
            
            # 等待进程结束
            local wait_time=0
            local max_wait=30
            while kill -0 $PID 2>/dev/null && [[ $wait_time -lt $max_wait ]]; do
                sleep 1
                ((wait_time++))
                echo -n "."
            done
            
            if kill -0 $PID 2>/dev/null; then
                log_warning "应用未响应，强制停止..."
                kill -9 $PID
            fi
            
            rm -f app.pid
            log_success "主应用已停止"
        else
            log_warning "应用进程不存在，清理PID文件"
            rm -f app.pid
        fi
    else
        log_info "主应用未运行"
    fi
}

# 停止用户环境
stop_user_environments() {
    log_info "停止用户环境..."
    
    if [[ -d "users" ]]; then
        local user_dirs=($(find users -maxdepth 1 -type d -name "user*" 2>/dev/null))
        local total_users=${#user_dirs[@]}
        
        if [[ $total_users -gt 0 ]]; then
            echo "发现 $total_users 个用户环境，正在停止..."
            
            for user_dir in "${user_dirs[@]}"; do
                local user_id=$(basename "$user_dir")
                local compose_file="$user_dir/docker-compose.yml"
                
                if [[ -f "$compose_file" ]]; then
                    log_info "停止用户环境: $user_id"
                    cd "$user_dir"
                    
                    if docker-compose down 2>/dev/null; then
                        echo "  ✅ $user_id: 已停止"
                    else
                        echo "  ⚠️  $user_id: 停止失败"
                    fi
                    
                    cd - > /dev/null
                fi
            done
        else
            log_info "无用户环境需要停止"
        fi
    else
        log_info "用户目录不存在"
    fi
}

# 停止核心服务
stop_core_services() {
    log_info "停止核心服务..."
    
    # 停止MySQL
    if docker ps | grep -q practice-platform-mysql; then
        log_info "停止MySQL服务..."
        docker stop practice-platform-mysql
        log_success "MySQL服务已停止"
    else
        log_info "MySQL服务未运行"
    fi
    
    # 停止Redis
    if docker ps | grep -q practice-platform-redis; then
        log_info "停止Redis服务..."
        docker stop practice-platform-redis
        log_success "Redis服务已停止"
    else
        log_info "Redis服务未运行"
    fi
    
    # 停止RabbitMQ
    if docker ps | grep -q practice-platform-rabbitmq; then
        log_info "停止RabbitMQ服务..."
        docker stop practice-platform-rabbitmq
        log_success "RabbitMQ服务已停止"
    else
        log_info "RabbitMQ服务未运行"
    fi
    
    # 停止Elasticsearch
    if docker ps | grep -q practice-platform-elasticsearch; then
        log_info "停止Elasticsearch服务..."
        docker stop practice-platform-elasticsearch
        log_success "Elasticsearch服务已停止"
    else
        log_info "Elasticsearch服务未运行"
    fi
}

# 清理临时文件
cleanup_temp_files() {
    log_info "清理临时文件..."
    
    # 清理PID文件
    rm -f app.pid
    
    # 清理临时日志
    rm -f logs/*.tmp 2>/dev/null || true
    
    log_success "临时文件清理完成"
}

# 显示停止结果
show_stop_result() {
    echo
    echo "=========================================="
    echo "停止结果"
    echo "=========================================="
    
    # 检查主应用
    if [[ -f "app.pid" ]]; then
        local PID=$(cat app.pid)
        if kill -0 $PID 2>/dev/null; then
            echo "❌ 主应用: 仍在运行 (PID: $PID)"
        else
            echo "✅ 主应用: 已停止"
        fi
    else
        echo "✅ 主应用: 已停止"
    fi
    
    # 检查端口监听
    if netstat -tlnp 2>/dev/null | grep -q ":8080"; then
        echo "❌ 端口8080: 仍在监听"
    else
        echo "✅ 端口8080: 已释放"
    fi
    
    # 检查Docker容器
    local running_containers=$(docker ps --format "{{.Names}}" | grep -E "(practice-platform|mysql|redis|rabbitmq|elasticsearch)" || true)
    if [[ -n "$running_containers" ]]; then
        echo "❌ 仍有容器运行:"
        echo "$running_containers" | while read container; do
            echo "  - $container"
        done
    else
        echo "✅ 所有容器已停止"
    fi
    
    echo "=========================================="
}

# 显示重启命令
show_restart_commands() {
    echo
    echo "=========================================="
    echo "重启命令"
    echo "=========================================="
    echo "启动平台:   ./scripts/start.sh"
    echo "查看状态:   ./scripts/status.sh"
    echo "=========================================="
}

# 主函数
main() {
    echo "=========================================="
    echo "工程实践平台停止脚本"
    echo "=========================================="
    echo
    
    # 检查环境
    check_project_root
    
    # 停止服务
    stop_main_app
    stop_user_environments
    stop_core_services
    
    # 清理
    cleanup_temp_files
    
    # 显示结果
    show_stop_result
    show_restart_commands
    
    log_success "平台停止完成！"
}

# 执行主函数
main "$@" 